//
//  ContentView.swift
//  VideoToAudio
//
//  Created by 刘海康 on 2025/8/8.
//

import SwiftUI
import AVFoundation
import PhotosUI
import UniformTypeIdentifiers

struct ContentView: View {
    @State private var selectedVideo: PhotosPickerItem?
    @State private var videoURL: URL?
    @State private var isConverting = false
    @State private var conversionProgress: Float = 0.0
    @State private var showAlert = false
    @State private var alertMessage = ""
    @State private var audioURL: URL?
    @State private var showShareSheet = false
    @State private var isPlaying = false
    @State private var audioPlayer: AVAudioPlayer?
    @State private var playbackProgress: Float = 0.0
    @State private var playbackTimer: Timer?
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 30) {
                // 标题
                VStack {
                    Image(systemName: "video.badge.plus")
                        .font(.system(size: 60))
                        .foregroundColor(.blue)
                    Text("视频转音频")
                        .font(.largeTitle)
                        .fontWeight(.bold)
                    Text("选择视频文件，转换为音频格式")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
                .padding(.top, 50)
                
                Spacer()
                
                // 视频选择区域
                VStack(spacing: 20) {
                    if let videoURL = videoURL {
                        // 显示选中的视频信息
                        VStack {
                            Image(systemName: "video.fill")
                                .font(.system(size: 40))
                                .foregroundColor(.green)
                            Text("已选择视频")
                                .font(.headline)
                            Text(videoURL.lastPathComponent)
                                .font(.caption)
                                .foregroundColor(.secondary)
                                .lineLimit(1)
                        }
                        .padding()
                        .background(Color.green.opacity(0.1))
                        .cornerRadius(12)
                    } else {
                        // 视频选择按钮
                        PhotosPicker(selection: $selectedVideo, matching: .videos) {
                            VStack(spacing: 15) {
                                Image(systemName: "plus.circle.fill")
                                    .font(.system(size: 50))
                                    .foregroundColor(.blue)
                                Text("选择视频")
                                    .font(.headline)
                                Text("点击选择要转换的视频文件")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            .padding(40)
                            .background(Color.blue.opacity(0.1))
                            .cornerRadius(12)
                        }
                    }
                }
                
                // 转换按钮
                if videoURL != nil && !isConverting {
                    VStack(spacing: 12) {
                        Button(action: convertVideoToAudio) {
                            HStack(spacing: 8) {
                                Image(systemName: "arrow.triangle.2.circlepath")
                                    .font(.title2)
                                Text("开始转换")
                                    .font(.body)
                                    .fontWeight(.medium)
                            }
                            .foregroundColor(.white)
                            .padding(.vertical, 16)
                            .padding(.horizontal, 20)
                            .frame(maxWidth: .infinity, minHeight: 50)
                            .background(Color.blue)
                            .cornerRadius(12)
                        }
                        
                        // 如果已经转换完成，显示转换新视频的快捷按钮
                        if audioURL != nil {
                            Button(action: resetToVideoSelection) {
                                HStack(spacing: 8) {
                                    Image(systemName: "plus.circle")
                                        .font(.title2)
                                    Text("转换新视频")
                                        .font(.body)
                                        .fontWeight(.medium)
                                }
                                .foregroundColor(.white)
                                .padding(.vertical, 16)
                                .padding(.horizontal, 20)
                                .frame(maxWidth: .infinity, minHeight: 50)
                                .background(Color.purple)
                                .cornerRadius(12)
                            }
                        }
                    }
                    .padding(.horizontal)
                }
                
                // 转换进度
                if isConverting {
                    VStack(spacing: 15) {
                        ProgressView(value: conversionProgress)
                            .progressViewStyle(LinearProgressViewStyle())
                            .scaleEffect(x: 1, y: 2, anchor: .center)
                        
                        Text("正在转换... \(Int(conversionProgress * 100))%")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    .padding(.horizontal)
                }
                
                // 音频操作按钮
                if let audioURL = audioURL {
                    VStack(spacing: 12) {
                        // 分享按钮
                        Button(action: { showShareSheet = true }) {
                            HStack(spacing: 8) {
                                Image(systemName: "square.and.arrow.up")
                                    .font(.title2)
                                Text("分享音频")
                                    .font(.body)
                                    .fontWeight(.medium)
                            }
                            .foregroundColor(.white)
                            .padding(.vertical, 16)
                            .padding(.horizontal, 20)
                            .frame(maxWidth: .infinity, minHeight: 50)
                            .background(Color.blue)
                            .cornerRadius(12)
                        }
                        
                        // 保存音频按钮
                        Button(action: saveToPhotosLibrary) {
                            HStack(spacing: 8) {
                                Image(systemName: "folder.badge.plus")
                                    .font(.title2)
                                Text("保存音频")
                                    .font(.body)
                                    .fontWeight(.medium)
                            }
                            .foregroundColor(.white)
                            .padding(.vertical, 16)
                            .padding(.horizontal, 20)
                            .frame(maxWidth: .infinity, minHeight: 50)
                            .background(Color.green)
                            .cornerRadius(12)
                        }
                        
                        // 播放控制
                        VStack(spacing: 12) {
                            HStack(spacing: 12) {
                                Button(action: togglePlayback) {
                                    HStack(spacing: 8) {
                                        Image(systemName: isPlaying ? "pause.circle.fill" : "play.circle.fill")
                                            .font(.title2)
                                        Text(isPlaying ? "暂停" : "播放")
                                            .font(.body)
                                            .fontWeight(.medium)
                                    }
                                    .foregroundColor(.white)
                                    .padding(.vertical, 16)
                                    .padding(.horizontal, 20)
                                    .frame(maxWidth: .infinity, minHeight: 50)
                                    .background(Color.orange)
                                    .cornerRadius(12)
                                }
                                
                                Button(action: stopPlayback) {
                                    HStack(spacing: 8) {
                                        Image(systemName: "stop.circle.fill")
                                            .font(.title2)
                                        Text("停止")
                                            .font(.body)
                                            .fontWeight(.medium)
                                    }
                                    .foregroundColor(.white)
                                    .padding(.vertical, 16)
                                    .padding(.horizontal, 20)
                                    .frame(maxWidth: .infinity, minHeight: 50)
                                    .background(Color.red)
                                    .cornerRadius(12)
                                }
                            }
                            
                            // 播放进度条
                            if audioPlayer != nil {
                                VStack(spacing: 8) {
                                    ProgressView(value: playbackProgress)
                                        .progressViewStyle(LinearProgressViewStyle())
                                        .scaleEffect(x: 1, y: 1.5, anchor: .center)
                                    
                                    HStack {
                                        Text(formatTime(audioPlayer?.currentTime ?? 0))
                                            .font(.caption)
                                            .foregroundColor(.secondary)
                                        
                                        Spacer()
                                        
                                        Text(formatTime(audioPlayer?.duration ?? 0))
                                            .font(.caption)
                                            .foregroundColor(.secondary)
                                    }
                                }
                                .padding(.horizontal, 4)
                            }
                        }
                        
                        // 文件信息
                        VStack(spacing: 8) {
                            Text("音频文件信息")
                                .font(.subheadline)
                                .fontWeight(.medium)
                            
                            HStack {
                                Image(systemName: "doc.text")
                                Text(audioURL.lastPathComponent)
                                    .font(.caption)
                                    .lineLimit(1)
                                Spacer()
                            }
                            .padding(.horizontal, 12)
                            .padding(.vertical, 8)
                            .background(Color.gray.opacity(0.1))
                            .cornerRadius(8)
                        }
                        
                        // 重新选择视频按钮
                        Button(action: resetToVideoSelection) {
                            HStack(spacing: 8) {
                                Image(systemName: "arrow.clockwise")
                                    .font(.title2)
                                Text("重新选择视频")
                                    .font(.body)
                                    .fontWeight(.medium)
                            }
                            .foregroundColor(.white)
                            .padding(.vertical, 16)
                            .padding(.horizontal, 20)
                            .frame(maxWidth: .infinity, minHeight: 50)
                            .background(Color.purple)
                            .cornerRadius(12)
                        }
                    }
                    .padding(.horizontal)
                }
                
                Spacer(minLength: 50)
            }
            .padding()
            }
            .navigationTitle("视频转音频")
            .navigationBarTitleDisplayMode(.inline)
            .onChange(of: selectedVideo) { newValue in
                Task {
                    await loadVideo()
                }
            }
            .alert("提示", isPresented: $showAlert) {
                Button("确定") { }
            } message: {
                Text(alertMessage)
            }
            .sheet(isPresented: $showShareSheet) {
                if let audioURL = audioURL {
                    ShareSheet(items: [audioURL])
                }
            }
        }
    }
    
    private func loadVideo() async {
        guard let selectedVideo = selectedVideo else { return }
        
        do {
            if let videoData = try await selectedVideo.loadTransferable(type: Data.self) {
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let videoFileName = "selected_video_\(Date().timeIntervalSince1970).mov"
                let videoFileURL = documentsDirectory.appendingPathComponent(videoFileName)
                
                try videoData.write(to: videoFileURL)
                await MainActor.run {
                    self.videoURL = videoFileURL
                }
            }
        } catch {
            await MainActor.run {
                alertMessage = "加载视频失败: \(error.localizedDescription)"
                showAlert = true
            }
        }
    }
    
    private func convertVideoToAudio() {
        guard let videoURL = videoURL else { return }
        
        isConverting = true
        conversionProgress = 0.0
        
        Task {
            do {
                let audioURL = try await performConversion(videoURL: videoURL)
                await MainActor.run {
                    self.audioURL = audioURL
                    self.isConverting = false
                    self.conversionProgress = 1.0
                    self.alertMessage = "转换完成！"
                    self.showAlert = true
                }
            } catch {
                await MainActor.run {
                    self.isConverting = false
                    self.alertMessage = "转换失败: \(error.localizedDescription)"
                    self.showAlert = true
                }
            }
        }
    }
    
    private func performConversion(videoURL: URL) async throws -> URL {
        let asset = AVAsset(url: videoURL)
        
        // 创建导出会话
        guard let exportSession = AVAssetExportSession(
            asset: asset,
            presetName: AVAssetExportPresetAppleM4A
        ) else {
            throw ConversionError.exportSessionCreationFailed
        }
        
        // 设置输出URL
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let audioFileName = "converted_audio_\(Date().timeIntervalSince1970).m4a"
        let audioURL = documentsDirectory.appendingPathComponent(audioFileName)
        
        // 删除已存在的文件
        if FileManager.default.fileExists(atPath: audioURL.path) {
            try FileManager.default.removeItem(at: audioURL)
        }
        
        exportSession.outputURL = audioURL
        exportSession.outputFileType = .m4a
        exportSession.shouldOptimizeForNetworkUse = true
        
        // 开始转换
        await exportSession.export()
        
        // 检查转换结果
        switch exportSession.status {
        case .completed:
            return audioURL
        case .failed:
            throw exportSession.error ?? ConversionError.conversionFailed
        case .cancelled:
            throw ConversionError.conversionCancelled
        default:
            throw ConversionError.unknownError
        }
    }
    
    private func saveToPhotosLibrary() {
        guard let audioURL = audioURL else { return }
        
        Task {
            do {
                // 检查照片库权限
                let status = PHPhotoLibrary.authorizationStatus(for: .addOnly)
                
                if status == .notDetermined {
                    let granted = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
                    if granted != .authorized {
                        throw SaveError.permissionDenied
                    }
                } else if status != .authorized {
                    throw SaveError.permissionDenied
                }
                
                // 尝试保存到照片库（iOS 14+支持音频）
                if #available(iOS 14.0, *) {
                    try await PHPhotoLibrary.shared().performChanges {
                        let request = PHAssetCreationRequest.forAsset()
                        request.addResource(with: .audio, fileURL: audioURL, options: nil)
                    }
                    
                    await MainActor.run {
                        alertMessage = "音频已成功保存到照片库！"
                        showAlert = true
                    }
                } else {
                    // iOS 14以下版本，保存到文件应用
                    try await saveToFiles()
                }
            } catch {
                // 如果保存到照片库失败，尝试保存到文件应用
                do {
                    try await saveToFiles()
                } catch {
                    await MainActor.run {
                        alertMessage = "保存失败: \(error.localizedDescription)"
                        showAlert = true
                    }
                }
            }
        }
    }
    
    private func saveToFiles() async throws {
        guard let audioURL = audioURL else { return }
        
        // 创建临时文件用于分享
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let fileName = "converted_audio_\(Date().timeIntervalSince1970).m4a"
        let destinationURL = documentsDirectory.appendingPathComponent(fileName)
        
        // 复制文件
        try FileManager.default.copyItem(at: audioURL, to: destinationURL)
        
        await MainActor.run {
            // 显示文件保存成功消息
            alertMessage = "音频已保存到文件应用！\n文件名: \(fileName)"
            showAlert = true
        }
    }
    
    private func togglePlayback() {
        guard let audioURL = audioURL else { return }
        
        if isPlaying {
            // 暂停播放
            audioPlayer?.pause()
            isPlaying = false
            playbackTimer?.invalidate()
            playbackTimer = nil
        } else {
            // 开始播放
            if audioPlayer == nil {
                // 首次播放，创建播放器
                do {
                    audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
                    audioPlayer?.delegate = nil
                    audioPlayer?.prepareToPlay()
                } catch {
                    alertMessage = "播放失败: \(error.localizedDescription)"
                    showAlert = true
                    return
                }
            }
            
            // 开始播放
            audioPlayer?.play()
            isPlaying = true
            
            // 启动进度更新定时器
            startPlaybackTimer()
        }
    }
    
    private func stopPlayback() {
        audioPlayer?.stop()
        audioPlayer = nil
        isPlaying = false
        playbackProgress = 0.0
        playbackTimer?.invalidate()
        playbackTimer = nil
    }
    
    private func startPlaybackTimer() {
        playbackTimer?.invalidate()
        playbackTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
            updatePlaybackProgress()
        }
    }
    
    private func updatePlaybackProgress() {
        guard let player = audioPlayer else { return }
        
        if player.duration > 0 {
            playbackProgress = Float(player.currentTime / player.duration)
        }
        
        // 检查播放是否结束
        if !player.isPlaying && isPlaying {
            isPlaying = false
            playbackProgress = 0.0
            playbackTimer?.invalidate()
            playbackTimer = nil
        }
    }
    
    private func formatTime(_ time: TimeInterval) -> String {
        let minutes = Int(time) / 60
        let seconds = Int(time) % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
    
    private func resetToVideoSelection() {
        // 停止播放
        stopPlayback()
        
        // 清理状态
        selectedVideo = nil
        videoURL = nil
        audioURL = nil
        isConverting = false
        conversionProgress = 0.0
        
        // 清理临时文件
        cleanupTempFiles()
    }
    
    private func cleanupTempFiles() {
        Task {
            let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            
            do {
                let files = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)
                let tempFiles = files.filter { $0.lastPathComponent.contains("selected_video_") || $0.lastPathComponent.contains("converted_audio_") }
                
                for file in tempFiles {
                    try FileManager.default.removeItem(at: file)
                }
            } catch {
                print("清理临时文件失败: \(error)")
            }
        }
    }
}

// 分享表单
struct ShareSheet: UIViewControllerRepresentable {
    let items: [Any]
    
    func makeUIViewController(context: Context) -> UIActivityViewController {
        let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
        
        // 设置分享选项
        activityViewController.excludedActivityTypes = [
            .assignToContact,
            .addToReadingList,
            .openInIBooks,
            .markupAsPDF
        ]
        
        // 设置分享标题
        activityViewController.setValue("分享音频文件", forKey: "subject")
        
        return activityViewController
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}

// 错误枚举
enum ConversionError: Error, LocalizedError {
    case exportSessionCreationFailed
    case conversionFailed
    case conversionCancelled
    case unknownError
    
    var errorDescription: String? {
        switch self {
        case .exportSessionCreationFailed:
            return "无法创建导出会话"
        case .conversionFailed:
            return "转换失败"
        case .conversionCancelled:
            return "转换已取消"
        case .unknownError:
            return "未知错误"
        }
    }
}

enum SaveError: Error, LocalizedError {
    case permissionDenied
    case fileSystemError
    case unsupportedFormat
    
    var errorDescription: String? {
        switch self {
        case .permissionDenied:
            return "需要照片库访问权限"
        case .fileSystemError:
            return "文件系统错误"
        case .unsupportedFormat:
            return "不支持的格式"
        }
    }
}

#Preview {
    ContentView()
}
